//
//  XGTokenUserAccount.swift
//  WeIBo
//
//  Created by 苏文潇 on 2017/3/8.
//  Copyright © 2017年 苏文潇. All rights reserved.
//

import UIKit

//授权参数和用户参数
class XGTokenUserAccount: NSObject, NSCoding {


//    用户令牌
    var access_token: String?
//    token的生命周期（即多久后过期，单位秒）
    var expires_in: TimeInterval = 0 {
        
        didSet{
//            过期日期 = 当前取到的时间 + 过期时间
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    
//    过期日期(添加字段)
    var expiresDate: Date?
    
//    用户的UID
    var uid: Int64 = 0
    
//    用户名
    var name: String?
//    用户头像(大图)
    var avatar_large: String?
    
    
//    kvc构造函数
    init(dic:[String : Any]) {
        
        super.init()
        
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
//    归档
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
//    解挡
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    
//    保存用户对象
    func saveUserAccount(){
        
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.archive")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
//    获取对象
    class func loadUserAccount() -> XGTokenUserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.archive")
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
        return userAccount as? XGTokenUserAccount
    }
    
    
}




